// @ts-ignore
import rs from 'jsrsasign';
import uuid from './uuid';
import stringMd5 from './FSTool/stringMd5';

let RSATool = {
    createKey(b = 2048) {
        let rsaKeypair = rs.KEYUTIL.generateKeypair('RSA', b);
        // 密钥对象获取 pem 格式的密钥
        let publicDer: string = rs.KEYUTIL.getPEM(rsaKeypair.pubKeyObj);
        let privateDer: string = rs.KEYUTIL.getPEM(rsaKeypair.prvKeyObj, 'PKCS8PRV');
        return {privateDer, publicDer};
    },

    createJWT(ip: string, secure_key: string) {
        const tNow = rs.KJUR.jws.IntDate.get('now');
        const tEnd = rs.KJUR.jws.IntDate.get('now + 1day');
        const oPayload = {
            iss: 'WangShan',
            sub: 'NodeServer',
            nbf: tNow,
            iat: tNow,
            exp: tEnd,
            jti: uuid(),
            aud: ip
        };
        const sHeader = JSON.stringify({alg: 'HS256', typ: 'JWT'});
        const sPayload = JSON.stringify(oPayload);
        return rs.KJUR.jws.JWS.sign('HS256', sHeader, sPayload, stringMd5(secure_key));
    },

    verifyJWT(jwt: string, ip: string, secure_key: string) {
        return rs.KJUR.jws.JWS.verifyJWT(jwt, stringMd5(secure_key), {
            alg: ['HS256'],
            aud: [ip],  // 显式验证aud字段
            iss: ['WangShan'],
            gracePeriod: 300  // 允许5分钟时钟偏移[5](@ref)
        });
    }
};


export default RSATool;
